package com.dtsz.m2.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.dtsz.m2.MainActivity;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.refresh.LoadingFooter;
import com.dtsz.m2.ui.adapter.TaskAdatper;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.HomeVo;
import com.dtsz.m2.ui.model.MwRecordVo;
import com.dtsz.m2.ui.model.TaskCount;
import com.dtsz.m2.ui.model.TaskOrder;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.utils.TaskCountdownUtils;
import com.dtsz.m2.volley.state.HUCState;

import java.util.ArrayList;
import java.util.List;


public class TaskActivity extends BaseActivity implements com.dtsz.m2.refresh.xRecyclerView.OnRefreshListener {
    private View view;
    private TextView tvTask, tvNum, tvName;

    private TaskAdatper taskAdatper;
    private com.dtsz.m2.refresh.xRecyclerView xRecyclerView;
    private List<TaskOrder> noticeList = new ArrayList<>();
    private boolean refreshFlag = true;

    private TaskCountdownUtils taskCountdownUtils;


    private AlertDialog alertDialog1;

//    private ShowRewardAD showRewardAd;
    private final String TAG = "emmmmmmmmmmm";
    private TTAdNative mTTAdNative;
    private AdSlot adSlot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_task);
        super.onCreate(savedInstanceState);

        mTTAdNative= TTAdSdk.getAdManager().createAdNative(this);
        adSlot = new AdSlot.Builder()
                .setCodeId("947069488")
//                .setRewardName("m2")
//                .setRewardAmount(1)
                .setExpressViewAcceptedSize(500,500)
                .setUserID("user0")//tag_id
                .setMediaExtra("media_extra") //附加参数
                .setOrientation(TTAdConstant.VERTICAL)
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .build();


        taskAdatper = new TaskAdatper(this, R.layout.item_order, noticeList);
        xRecyclerView.setAdapter(this, taskAdatper, new LinearLayoutManager(this));
        xRecyclerView.setOnRefreshListener(this);

        getTaskCount();
    }

    private void loadAd() {
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
            }
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                loadDismiss();
                ad.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() {
                        Log.i(TAG, "onAdShow: ");
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        Log.i(TAG, "onAdVideoBarClick: ");
                    }

                    @Override
                    public void onAdClose() {
                        Log.i(TAG, "onAdClose: ");
                    }

                    @Override
                    public void onVideoComplete() {
                        Log.i(TAG, "onVideoComplete: ");
                    }

                    @Override
                    public void onVideoError() {
                        Log.i(TAG, "onVideoError: ");
                    }

                    @Override
                    public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                    }

                    @Override
                    public void onRewardArrived(boolean b, int i, Bundle bundle) {
                        addTask();
                    }

                    @Override
                    public void onSkippedVideo() {
                        Log.i(TAG, "onSkippedVideo: ");
                    }
                });
                ad.setRewardPlayAgainInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() {
                        Log.i(TAG, "onAdShow: ");
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        Log.i(TAG, "onAdVideoBarClick: ");
                    }

                    @Override
                    public void onAdClose() {
                        Log.i(TAG, "onAdClose: ");
                    }

                    @Override
                    public void onVideoComplete() {
                        Log.i(TAG, "onVideoComplete: ");
                    }

                    @Override
                    public void onVideoError() {
                        Log.i(TAG, "onVideoError: ");
                    }

                    @Override
                    public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {
                    }
                    @Override
                    public void onRewardArrived(boolean b, int i, Bundle bundle) {
                        addTask();
                    }

                    @Override
                    public void onSkippedVideo() {
                        Log.i(TAG, "onSkippedVideo: ");
                    }
                });
                ad.showRewardVideoAd(TaskActivity.this);
            }
            @Override
            public void onRewardVideoCached() {
            }
            @Override
            public void onRewardVideoCached(TTRewardVideoAd ad) {
            }
        });

    }

    @Override
    public void initView() {
        super.initView();
        xRecyclerView = findViewById(R.id.xrecyclerView);
        view = findViewById(R.id.ll_show_end);
        tvTask = findViewById(R.id.tv_task);
        tvNum = findViewById(R.id.tv_num);
        tvName = findViewById(R.id.tv_name);
    }

    @Override
    public void initUtils() {
        super.initUtils();
    }

    @Override
    public void initClick() {
        super.initClick();
        view.setOnClickListener(this);
        findViewById(R.id.lay_actionbar_left);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_actionbar_left:
                finish();
                break;
            case R.id.ll_show_end:
                String taskStr = tvTask.getText().toString();
                if ("开始任务".equals(taskStr)) {
//                    view.setClickable(false);
                    loading();
                    loadAd();
                }
                if (!"已完成".equals(taskStr) && !"开始任务".equals(taskStr)) {
                    showToast("倒计时结束之后，任务继续");
                }
                break;
        }
    }
    @SuppressLint({"NotifyDataSetChanged", "SetTextI18n"})
    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof TaskCount) {
                    TaskCount taskCount = (TaskCount) response;
                    String price = taskCount.getPrice();
                    if (StringUtils.isEmpty(price)) {
                        tvName.setText("任务收益:0.00㎡");
                    } else {
                        tvName.setText("任务收益:" + price + "㎡");
                    }
                    String num = taskCount.getNum();
                    if (StringUtils.isEmpty(num)) {
                        num = "0";
                    }
                    int number = Integer.parseInt(num);
                    String clickNum = taskCount.getClickNum();
                    tvNum.setText("任务完成进度（" + number + "/" + clickNum + "）");
                    if (number >= Integer.parseInt(clickNum)) {
                        view.clearAnimation();
                        tvTask.setText("已完成");
                        tvTask.setTextColor(getResources().getColor(R.color.colorFont2));
                        //tvTask.setTextColor(getResources().getColor(R.color.colorFont2, null));
                        view.setBackgroundResource(R.drawable.radius100_gray);
                    } else {
                        ScaleAnimation scaleAnimation = (ScaleAnimation) AnimationUtils.loadAnimation(this, R.anim.scale);
                        view.startAnimation(scaleAnimation);
                        view.setBackgroundResource(R.drawable.radius100_blue);
                        if (number * 2 == Integer.parseInt(clickNum)) {
                            String isNum1 = taskCount.getClickNum1();
                            if ("0".equals(isNum1)) {
                                tvTask.setText("开始任务");
                            } else {
                                taskCountdownUtils = new TaskCountdownUtils(this, tvTask, Long.parseLong(taskCount.getDateLong()), 1000);
                                taskCountdownUtils.setButtonClick("开始任务");
                                taskCountdownUtils.start();
                            }
                        } else {
                            tvTask.setText("开始任务");
                        }
                        tvTask.setTextColor(getResources().getColor(R.color.colorFont11));
                        //tvTask.setTextColor(getResources().getColor(R.color.colorFont11, null));
                    }
                }
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof List) {
                    List<TaskOrder> noticeLists = (List<TaskOrder>) response;
                    if (refreshFlag) {
                        if (noticeLists.size() == 0) {
                            if (noticeList.size() == 0) {
                                xRecyclerView.refreshComplete(LoadingFooter.State.NoData, "");
                            } else {
                                xRecyclerView.refreshComplete(LoadingFooter.State.TheEnd, "");
                            }
                        } else {
                            noticeList.addAll(noticeLists);
                            taskAdatper.notifyDataSetChanged();
                            xRecyclerView.refreshComplete(LoadingFooter.State.Normal, "");
                        }
                    } else {
                        noticeList.clear();
                        noticeList.addAll(noticeLists);
                        taskAdatper.notifyDataSetChanged();
                        xRecyclerView.refreshComplete(LoadingFooter.State.Normal, "");
                    }
                }
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                HomeVo homeVo = (HomeVo) response;
                String msg = homeVo.getYesSum();
                if (!"保存失败".equals(msg)) {
                    String isMedal = homeVo.getIsMedal();
                    if ("1".equals(isMedal)) {
                        setMealdlAlert(homeVo);
                    }
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "任务奖励：" + msg + "㎡", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    getTaskCount();
                    refreshFlag = false;
                    onStart();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_7:
                String re = (String) response;
                if ("成功".equals(re)) {
                    alertDialog1.dismiss();
                    sendIntent(this, MedalWallActivity.class);
                } else {
                    showToast(re);
                }
                break;
        }
        loadDismiss();
    }

    private void getTaskCount() {
        //获取网络数据
        loading();
        hucRequestInterfase.executeStr(this, TaskCount.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.TASKCOUNT_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }


    @Override
    public void refresh(SwipeRefreshLayout refreshLayout) {
        refreshFlag = false;
        onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (showRewardAd != null) {
//            showRewardAd.destroy();
//        }
    }

    @Override
    public void loadMore(RecyclerView recyclerView) {
        refreshFlag = true;
        int CurrentCount = Integer.parseInt(pageVo.getCurrent()) + 1;
        pageVo.setCurrent(CurrentCount + "");
        pageVo.setSize(10 + "");
        getInitData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        refreshFlag = false;
        pageVo.setCurrent(1 + "");
        pageVo.setSize(10 + "");
        getInitData();
    }

    private void getInitData() {
        pageVo.setIndex("2");
        loading();
        hucRequestInterfase.executeStr(this, TaskOrder.class,
                HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.TASKS_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
    }

    private void addTask() {
        pageVo.setBoType("视频任务奖励");
        loading();
        hucRequestInterfase.executeStr(this, HomeVo.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.ADDTASK_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @SuppressLint("SetTextI18n")
    private void setMealdlAlert(HomeVo homeVo) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(this).inflate(R.layout.popupwindow_mealdl_alert, null);
        ImageView tvImage = root.findViewById(R.id.tv_image);
        Glide.with(this).load(homeVo.getLightUrl()).into(tvImage);
        TextView tvName = root.findViewById(R.id.tv_name);
        tvName.setText(homeVo.getName());
        TextView tvNum = root.findViewById(R.id.tv_num);
        tvNum.setText("+" + homeVo.getReward() + "㎡");
        dialog.setView(root);
        root.findViewById(R.id.tv_ok).setOnClickListener(v -> {
            MwRecordVo mwRecordVo = new MwRecordVo();
            mwRecordVo.setToken(pageVo.getToken());
            mwRecordVo.setLanguage("1");
            mwRecordVo.setGrade(homeVo.getGrade());
            mwRecordVo.setType(homeVo.getType());
            updateStatus(mwRecordVo);
        });
        root.findViewById(R.id.tv_del).setOnClickListener(v -> alertDialog1.dismiss());
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    void updateStatus(MwRecordVo mwRecordVo) {
        loading();
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_7, Request.Method.POST, UrlConfig.UPDATESTATUS_URL,
                hucParameInterfase.getRequestParameter(mwRecordVo), false);
    }

}
